<?php 
	header("Content-type: text/html; charset=utf-8");
	require_once('auth_i.inc.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>

<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<meta http-equiv="X-UA-Compatible" content="IE=8" />
	<link rel="stylesheet" type="text/css" media="screen" href="css/themes/redmond/jquery-ui-1.8.9.custom.css" />
	<link rel="stylesheet" type="text/css" media="screen" href="css/ui.jqgrid.css" />
	<link rel="stylesheet" type="text/css" media="screen" href="css/ui.multiselect.css" />
	<link rel="stylesheet" type="text/css" media="screen" href="css/asud.css" />

	<script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>
	<script src="js/i18n/grid.locale-ru.js" type="text/javascript"></script>
	<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
	<script src="js/jquery-ui-1.8.9.custom.min.js" type="text/javascript"></script>

<script type="text/javascript">

$(function() { 
  $("#master-list").jqGrid({
    url:'req/eve_list.php',
	editurl:'req/eve_edit.php',	
    datatype: 'json',
    mtype: 'GET',
    colNames:['Название'],
    colModel :[ 
      {name:'name', index:'name', width:185, editable: true, editoptions:{size:20}}, 
    ],
    sortname: 'name',
    sortorder: 'asc',
    viewrecords: true,
    width: 375,
	onSelectRow: function(ids) 
				{ 
					if(ids == null) 
					{ 
						ids=0; 

						if (jQuery("#detail-list").jqGrid('getGridParam','records') > 0 ) 
						{ 
							jQuery("#detail-list").jqGrid('setGridParam',
														{ 
															url:"req/det_list.php?eve=-1",
															page:1
														}); 

							jQuery("#detail-list").jqGrid('setCaption',"Событие: "+ids).trigger('reloadGrid'); 
						} 
					} 
					else 
					{ 
						var data = jQuery("#master-list").getRowData( ids );

						$('input[name="e_id"]').val(ids);
                                                
						jQuery("#detail-list").jqGrid('setGridParam',
													{
														url:"req/det_list.php?eve="+ids,
														page:1
													}); 

						jQuery("#detail-list").jqGrid('setCaption',"Событие: "+data.name).trigger('reloadGrid'); 
					} 
				}
  });

  var sel_type_vals = ["Группа", "Контроллер"]; 

  function format_sel_type(_cell_val, _options, _row_object)
  {
  	try
  	{
  		return sel_type_vals[_cell_val];
	}
	catch (e)
	{
		return "Ошибка";
	}
  }

  function unformat_sel_type(_cell_val, _options, _row_object)
  {
	var idx = sel_type_vals.indexOf(_cell_val);

  	return idx;
  }

  var act_type_vals = ["Программа", "Фаза"]; 

  function format_act_type(_cell_val, _options, _row_object)
  {
  	try
  	{
  		return act_type_vals[_cell_val];
	}
	catch (e)
	{
		return "Ошибка";
	}
  }

  function unformat_act_type(_cell_val, _options, _row_object)
  {
	var idx = act_type_vals.indexOf(_cell_val);

  	return idx;
  }

  var param_prg = ["Программа 0","Программа 1","Программа 2","Программа 3","Программа 4","Программа 5","Программа 6","Программа 7"];
  var param_phase = ["Фаза 0","Фаза 1","Фаза 2","Фаза 3","Фаза 4","Фаза 5","Фаза 6","Фаза 7","","","","","","","","Желтый мигающий","Отключить"];

  function gen_prog_opt()
  {
  	var value = "";
  	var cnt = 0;

  	param_prg.forEach(function(_value)
  		{
  			value += '<option value="' + cnt++ + '">' + _value + '</option>\n';
  		});

	return value;

  }

  function gen_phase_opt()
  {
  	var value = "";
  	var cnt = 0;

  	param_phase.forEach(function(_value)
  		{
  			if (_value != "")
  			{
  				value += '<option value="' + cnt + '">' + _value + '</option>\n';
			}
			cnt++;
  		});

	return value;

  }

  function format_act_param(_cell_val, _options, _row_object)
  {
  	try
  	{
   		if (_row_object[3] == 0)		// программа
   		{	
			return param_prg[_cell_val]
   		}
		else if (_row_object[3] == 1)		// фаза
		{
			return param_phase[_cell_val]
		}
	}
	catch(e)
	{
	}

	return "Ошибка"
  }

  function unformat_act_param(_cell_val, _options, _row_object)
  {

  	var idx = param_prg.indexOf(_cell_val);

   	if (idx > 0)
  		return idx
	else
		return param_phase.indexOf(_cell_val);
  }


 $("#detail-list").jqGrid({
    url:'req/det_list.php?eve=-1',
	editurl:'req/det_edit.php',	
    datatype: 'json',
    width: 375,
    mtype: 'GET',
    colNames:[ 'Тип','-', 'Имя', 'Вид', 'Имя' ],
    colModel :[ 

	  {name:'sel_type', index:'sel_type', align: "right", formatter: format_sel_type, unformat: unformat_sel_type},	
	  {name:'sel_param', index:'sel_param', hidden: true},	
	  {name:'sel_param_name', index:'sel_param_name', editable: false},	
	  {name:'act_type', index:'act_type', align: "right", formatter: format_act_type, unformat: unformat_act_type},	
	  {name:'act_param', index:'act_param', formatter: format_act_param, unformat: unformat_act_param, width:190 },

    ],
    sortname: 'sel_type',
    sortorder: 'asc',
    viewrecords: true,
 });

$( "#master-edit-button" )
			.button()
			.click(function() {
				var gr = jQuery("#master-list").jqGrid('getGridParam','selrow'); 

				if( gr != null ) 
					jQuery("#master-list").jqGrid('editGridRow',gr,{reloadAfterSubmit:false,closeAfterEdit:true}); 
				else 
					alert("Выбирите строку для редактирования !"); 
			});

$( "#master-add-button" )
			.button()
			.click(function() {
				jQuery("#master-list").jqGrid('editGridRow',"new",{reloadAfterSubmit:true,closeAfterAdd:true}); 
			});


$("#master-remove-button")
			.button()
			.click(function() { 

				var gr = $("#master-list").jqGrid('getGridParam','selrow'); 
				if( gr != null ) 
				{
					$("#master-list").jqGrid('delGridRow',gr,{reloadAfterSubmit:true,width: 300, msg:'Удалить событие со всем его седержимым ?'}); 
				}
				else 
				{
					alert("Выбирите строку для удаления !"); 
				}
			});

function setup_plist()
{
	if($('select[name="act_type"]').val() == 0)
	{
		$('select[name="act_param"]').html('<option value="-1">- Программа -</option>\n' + gen_prog_opt() +
		 		"</select>");
	}
	else
	{
		$('select[name="act_param"]').html('<option value="-1">--- Фаза ---</option>\n' + gen_phase_opt() +
				"</select>");
    }
}

function setup_list()
{
	$.ajaxSetup({async: false});

	if($('select[name="sel_type"]').val() == 0)
	{
		$.get('req/grp_opt.php?type=opt', 
			function(data)
				{
					$('select[name="sel_param"]').html('<option value="-1">--- Группа ---</option>\n' + data + "\n</select>");
				});

	}
	else
	{
		$.get('req/con_opt.php', 
			function(data)
				{
					$('select[name="sel_param"]').html('<option value="-1">- Контроллер -</option>\n' + data + "\n</select>");
				});
    }
}

$( "#set-event-item" ).dialog({
			autoOpen: false,
			modal: true,
			resizable: false,
			width: 350,

			buttons: {
				"Ok": function() 
				{
					if ($('select[name="sel_type"]').val() == -1)
					{
						alert('Не выбрана группа или контроллер !');
						return;
					}

					if ($('select[name="act_type"]').val() == -1)
					{
						alert('Не выбрано действие !');
						return;
					}

					$.ajaxSetup({async: false});

					var aa = $('#set-event-item-form').serialize();

					$.post('req/eve_edit.php', '&' + aa ,
						function(data)
						{
							$("#detail-list").trigger("reloadGrid");
						}
						);

						
					$( this ).dialog( "close" );
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
			},
			open: function (event, ui) {
				$('select[name="sel_type"]').change(function()
				{
					setup_list();
				});

				$('select[name="act_type"]').change(function()
				{
					setup_plist();
				});

			}
});

$("#detail-add-button")
			.button()
			.click(function() {
				var gr = jQuery("#master-list").jqGrid('getGridParam','selrow'); 

				if( gr != null ) 
				{
					setup_list();
					setup_plist();

					$( "#set-event-item" ).dialog("open");
				}
				else 
					alert("Выбирите событие для редактирование или добавления !"); 
			});

$("#detail-edit-button")
			.button()
			.click(function() {

				var grm = $("#master-list").getGridParam('selrow'); 
				var grd = $("#detail-list").getGridParam('selrow'); 

				if( grm == null ) 
				{
					alert("Выбирите событие для редактирование или добавления !"); 		
					return
				}

				if( grd == null ) 
				{
					alert("Выбирите строку для редактирование или добавления !");
					return;
				}

				var data = $("#detail-list").getRowData(grd);

				$('select[name="sel_type"]').val(data.sel_type);
				$('select[name="act_type"]').val(data.act_type);

				setup_list();
				setup_plist();

				$('#set-event-item select[name="sel_param"] option[value="' + data.sel_param +'"]').attr('selected', true);
				$('#set-event-item select[name="act_param"] option[value="' + data.act_param +'"]').attr('selected', true);

				$( "#set-event-item" ).dialog("open");

			});

}); 

</script>

</head>
<body>
<?php // menu bar
	require_once('menu.inc.php');

	print menu($menu_items, 'event.php');
?>

<div id="set-event-item" title="Добавить управление">
	<form id="set-event-item-form" class="FormGrid">
		<table id = "FormTable">
		 <tr id="FormRow">
		  <td id="FormTD">
		  	Переключить:	
		  </td>
		  <td id="FormTD">	
		    <select name="sel_type" size="1" class="FormElement ui-widget-content ui-corner-all">
		    	<option value='0' selected >Группу</option> 
	           	<option value='1'>Контроллер</option>
		    </select>
		  </td>

		  <td id="FormTD">	
		    <select name="sel_param" size="1" class="FormElement ui-widget-content ui-corner-all">
		    </select>
		  </td>

		  </tr>
  		  <tr id="FormRow">
		  <td id="FormTD">	
		  установить:
		  </td>
		  <td id="FormTD">	
		    <select name="act_type" size="1" class="FormElement ui-widget-content ui-corner-all">
		    	<option value='0' selected>программу</option> 
	           	<option value='1'>фазу</option>
		    </select>
		  </td>
		  <td id="FormTD">	
		    <select name="act_param" size="1" class="FormElement ui-widget-content ui-corner-all">
		    </select>
		  </td>
		 </tr>
		</table>
		<input type="hidden" name="e_id" value="-1"/>	
		<input type="hidden" name="oper" value="det-add"/>	
	</form>
</div>



<div id="main-box">
	<table id="master-list"></table> 
	<div id="button-box">	
		<button id="master-add-button">Добавить</button>
		<button id="master-edit-button">Редактировать</button>
		<button id="master-remove-button">Удалить</button>
	</div>
</div>
<div id="main-box">
	<table id="detail-list"></table> 
	<div id="button-box">	
		<button id="detail-add-button">Добавить</button>
		<button id="detail-edit-button">Редактировать</button>
		<button id="detail-remove-button">Удалить</button>
	</div>
</div>

</body>
</html>
